# coding: utf-8
from .models import UserProfile
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from users.serializers import UserSerializer
from rest_framework import mixins, status
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.authentication import SessionAuthentication
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from django.db.models import Q
from rest_framework.response import Response
from datetime import datetime, timedelta
import json


# 表分页配置
class TablePagination(PageNumberPagination):
    page_size = 20
    page_size_query_param = 'page_size'
    page_query_param = 'p'
    max_page_size = 10


# 用户登录接口
class UserProfileListViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    """
    用户登录接口
    """
    authentication_classes = ()
    # queryset = UserProfile.objects.all()
    # 返回序列化数据
    serializer_class = UserSerializer

    def create(self, request, *args, **kwargs):  # 用户登录返回token
        queryset = self.filter_queryset(self.get_queryset())

        ret = {'status': 'success', 'msg': None, 'user': None}
        serializer = self.get_serializer(context={'request': request}, data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
            user = serializer.validated_data  # 验证返回的数据

            if user is not None:
                queryset = queryset.filter(
                    # syfz_person，jsfz_person，zlfz_person 为多对多关联 ，taskprolist__sy_engineer 为一对多关联
                    Q(username=user)
                ).distinct()
            else:
                queryset = queryset.filter(Q(username=None)).distinct()

            lists = self.get_serializer(queryset, many=True).data[0]

            re_dict = {}
            refresh = RefreshToken.for_user(user)
            re_dict['token'] = str(refresh.access_token)
            ret['user'] = lists
            ret['msg'] = re_dict
        except Exception as e:
            print(e)
            ret['status'] = 'fail'
            try:
                ret['msg'] = e.detail['non_field_errors'][0]
            except Exception as e2:
                ret['msg'] = "登录错误"
        return JsonResponse(ret)